import { EventEmitter } from '@angular/core';
export class KeyDownBuffer {

  keydown = new EventEmitter<string>()

  private _keyHolding: string;

  get keyHodling() { return this._keyHolding; }

  private onkeydown = ((e: KeyboardEvent) => {
    e.preventDefault();
    e.stopPropagation();
    if (this._keyHolding !== e.key) {
      this.keydown.emit(this._keyHolding = e.key);
    }
    return false;
  }).bind(this);

  private onkeyup = ((e: KeyboardEvent) => {
    e.preventDefault();
    e.stopPropagation();
    this._keyHolding = null;
    return false
  }).bind(this);


  constructor(private elem = window.document.body, private useCapture = false) {
  }

  start() {
    this.stop();
    this.elem.addEventListener('keydown', this.onkeydown, this.useCapture);
    this.elem.addEventListener('keyup', this.onkeyup, this.useCapture);
    return this;
  }

  stop() {
    this._keyHolding = null;
    this.elem.removeEventListener('keydown', this.onkeydown, this.useCapture);
    this.elem.removeEventListener('keyup', this.onkeyup, this.useCapture);
    return this;
  }

}